﻿using Coldairarrow.Business.PB;
using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.PB
{
    [Route("/PB/[controller]/[action]")]
    public class PB_ProjectController : BaseApiController
    {
        #region DI
        private readonly MongoDBOptions _mongodbOptions;
        public PB_ProjectController(IPB_ProjectBusiness pB_ProjectBus, IOperator op, IOptions<MongoDBOptions> mongodbOptions)
        {
            _pB_ProjectBus = pB_ProjectBus;
            _Op = op;
            _mongodbOptions = mongodbOptions.Value;
        }

        IPB_ProjectBusiness _pB_ProjectBus { get; }
        //IPB_ProjectBusiness _PB_Buildingnumber { get; }

        IOperator _Op { get; }
        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<PB_ProjectDTO>> GetDataList(PageInput<ConditionDTO> input)
        {
            return await _pB_ProjectBus.GetDataListAsync(input);
        }

        /*
         * 创建人：崔楠
         * 创建时间：2020-0313 10:58
         * 描述：添加大屏项目详情接口
         */
        /// <summary>
        /// 无Token获取项目列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<PageResult<PB_ProjectDTO>> GetDataListNoToken(PageInput<ConditionDTO> input)
        {
            return await _pB_ProjectBus.GetDataListNoTokenAsync(input);
        }

        /// <summary>
        /// 根据货位获取库存信息
        /// </summary>
        /// <param name="StorAreaName">库区名称</param>
        /// <param name="RackName">货架 名称集合</param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<List<MaterialByLocaltion>> GetMaterialSumDataList(string StorAreaName, List<string> RackName)
        {
            return await _pB_ProjectBus.GetMaterialSumDataListAsync(StorAreaName, RackName);
        }

        /*
         * 创建人：崔楠
         * 创建时间：2020-0313 10:58
         * 描述：添加大屏项目详情接口
         */
        /// <summary>
        /// 大屏获取项目进展接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<PageResult<ProjectInfoDTO>> GetProjectInfoDataList(PageInput<ConditionDTO> input)
        {
            return await _pB_ProjectBus.GetProjectInfoDataListAsync(input);
        }

        /// <summary>
        /// 手写的vue页面带输入条件查询大屏项目进展
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<PageResult<ProjectInfoDTO>> GetProjectInfoDataListBySearch(PageInput<ConditionDTO> input)
        {
            //return await _pB_ProjectBus.GetProjectInfoDataListBySearchAsync(input);
            //牟。2022.8.2
            return await _pB_ProjectBus.GetProjectInfoDataListAsync(input);
        }

        /// <summary>
        /// 清单项目树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<TreeDataDTO>> GetDataListInfo()
        {
            return await _pB_ProjectBus.GetDataListInfo();
        }
        /// <summary>
        /// 通知单项目树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<TreeDataStockDTO>> GetdeliverGoodsListInfo(string ProjectName)
        {
            return await _pB_ProjectBus.GetdeliverGoodsListInfo(ProjectName);
        }
        /// <summary>
        /// 获取项目不带子集合的数据集
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<TreeDataDTO>> GetDataListMainInfo(string ObjectName)
        {
            return await _pB_ProjectBus.GetDataMainListInfo(ObjectName);
        }

        /// <summary>
        /// 获取当前负责人的项目
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<PB_ProjectBulidList>> GetProjectCurrentState()
        {
            var list = await _pB_ProjectBus.GetProjectCurrentState();
            return list;

        }
        [HttpPost]
        public async Task<PB_ProjectDTO> GetTheData(IdInputDTO input)
        {
            return await _pB_ProjectBus.GetTheDataAsync(input.id);
        }

        /// <summary>
        /// 查看项目回货信息
        /// </summary>
        /// <param name="ProjectId">项目id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<EndReturnNums>> GetProjectListDataAsync(PageInput<EndReturnConditionDTO> input)
        {
            return await _pB_ProjectBus.GetProjectListDataAsync(input);
        }

        /// <summary>
        /// 关闭项目接口
        /// </summary>
        /// <param name="ProjectId">项目id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task CloseProjectData(string ProjectId)
        {
            await _pB_ProjectBus.CloseProjectDataAsync(ProjectId);
        }

        /// <summary>
        /// 获取项目信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_ProjectDTO>> GetProjectData(PageInput<ConditionDTO> input)
        {
            return await _pB_ProjectBus.GetProjectDataAsync(input);
        }
        [HttpGet]
        /// <summary>
        /// 项目统计信息
        /// </summary>
        /// <returns></returns>
        public async Task<ProjectStatistics> projectStatisticsInfo(string projectId)
        {
            return await _pB_ProjectBus.projectStatisticsInfo(projectId);

        }

        /// <summary>
        /// 回货选择项目信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_ProjectReturnDTO>> GetProjectReturnDataList(PageInput<ProjectReturnConditionDTO> input)
        {
            return await _pB_ProjectBus.GetProjectReturnDataListAsync(input);
        }

        /// <summary>
        /// 项目导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import(IFormFile file)
        {
            string ReturnValue = string.Empty;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_Project>();
                var liststr = new List<string>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {

                    for (int i = 0; i < CountRow; i++)
                    {
                        if (i != 0)
                        {
                            ///实例化 项目
                            PB_Project commodity = new PB_Project();
                            var row = sheet.GetRow(i);

                            if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                            {
                                commodity.Id = IdHelper.GetId();
                                commodity.CreatorId = _Op.UserId;
                                commodity.CreateTime = DateTime.Now;
                                commodity.DeptId = _Op.Property.DepartmentId;
                                commodity.Deleted = false;
                                commodity.State = 0;
                                commodity.Name = row.GetCell(0).ToString();
                            }

                            if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                            {
                                commodity.Code = row.GetCell(1).ToString();
                            }
                            if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                            {
                                commodity.ContactsId = row.GetCell(2).ToString();
                            }

                            if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                            {
                                commodity.ProvinceId = row.GetCell(3).ToString();
                            }

                            if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0)
                            {
                                commodity.CityId = row.GetCell(4).ToString();
                            }

                            if (row.GetCell(5) != null && row.GetCell(5).ToString().Trim().Length > 0)
                            {
                                commodity.AreaId = row.GetCell(5).ToString();
                            }

                            if (row.GetCell(6) != null && row.GetCell(6).ToString().Trim().Length > 0)
                            {
                                commodity.Address = row.GetCell(6).ToString();
                            }
                            if (row.GetCell(7) != null && row.GetCell(7).ToString().Trim().Length > 0)
                            {
                                commodity.Businesstype = row.GetCell(7).ToString();
                            }
                            if (row.GetCell(8) != null && row.GetCell(8).ToString().Trim().Length > 0)
                            {
                                commodity.Purchaseandsalesunit = row.GetCell(8).ToString();
                            }
                            if (row.GetCell(9) != null && row.GetCell(9).ToString().Trim().Length > 0)
                            {
                                commodity.Cooperativeunit = row.GetCell(9).ToString();
                            }
                            if (row.GetCell(10) != null && row.GetCell(10).ToString().Trim().Length > 0)
                            {
                                commodity.Signingunit = row.GetCell(10).ToString();
                            }
                            if (row.GetCell(11) != null && row.GetCell(11).ToString().Trim().Length > 0)
                            {
                                commodity.Remarks = row.GetCell(11).ToString();
                            }
                            commodity.CreateTime = DateTime.Now;
                            Data.Add(commodity);
                            liststr.Add(commodity.Code + "," + commodity.Name);
                        }


                    }

                    foreach (var item in Data)
                    {
                        var listdata = _pB_ProjectBus.GetQueryable<PB_Project>().Where(w => w.Name == item.Name && w.Code == item.Code);

                        if (listdata.Count() > 0)
                        {
                            foreach (var fu in listdata)
                            {
                                return Error(ReturnValue = "导入的数据中有已存在数据库中,请勿重复导入" + fu.Name);
                            }

                        }
                    }





                    if (Data.Count > 0)
                    {
                        try
                        {
                            await _pB_ProjectBus.AddDataExlAsync(Data);
                        }
                        catch (Exception ex)
                        {
                            string ErrLogCollection = "ErrLog";
                            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                            ErrLog err = new ErrLog()
                            {
                                Name = "项目导入",
                                Interface = "/PB/PB_Project/Import",
                                Type = "错误",
                                Time = DateTime.Now,
                                Remark = ex.Message
                            };
                            mongo.Add<ErrLog>(ErrLogCollection, err);
                        }
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";

                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题！" + ReturnValue);
                }
            }



            catch (Exception EX)
            {
                return Error("数据异常！");
            }
            return Success(ReturnValue);
        }



        /// <summary>
        /// 项目信息模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoCheckJWT]
        public IActionResult ExportToExcel()
        {
            //创建EXCEL工作薄
            IWorkbook workBook = new XSSFWorkbook();
            //创建sheet1文件表
            ISheet sheet = workBook.CreateSheet("项目信息");
            var expDir = string.Format("{0}Export\\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
                    DateTime.Now.ToString("yyyyMM"));

            if (!Directory.Exists(expDir)) Directory.CreateDirectory(expDir);

            string filePath = string.Format("{0}\\CD{1}.xlsx", expDir, DateTime.Now.ToString("yyyyMMddHHmmss"));

            #region 创建Excel表头(sheet1)
            //创建excel 表头
            IRow header = sheet.CreateRow(0);

            ICell cell = header.CreateCell(0);
            cell.SetCellValue("项目名称");




            cell = header.CreateCell(1);
            cell.SetCellValue("项目编号");

            cell = header.CreateCell(2);

            cell.SetCellValue("联系人");

            cell = header.CreateCell(3);
            cell.SetCellValue("省");

            cell = header.CreateCell(4);
            cell.SetCellValue("市");

            cell = header.CreateCell(5);
            cell.SetCellValue("区");

            cell = header.CreateCell(6);
            cell.SetCellValue("详情地址");

            cell = header.CreateCell(7);
            cell.SetCellValue("业务类型");

            cell = header.CreateCell(8);
            cell.SetCellValue("购销单位");

            cell = header.CreateCell(9);
            cell.SetCellValue("合作单位");

            cell = header.CreateCell(10);
            cell.SetCellValue("签订单位");

            cell = header.CreateCell(11);
            cell.SetCellValue("备注");


            #endregion

            //工作流写入，通过流的方式进行创建生成文件
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.Write(stream);
                byte[] buffer = stream.ToArray();

                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", string.Format("项目信息_{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")));
            }

        }

        [HttpPost]
        public async Task<string> GetLocation(string lng, string lat)
        {
            return await _pB_ProjectBus.GetLocation(lng, lat);
        }

        /// <summary>
        /// 获取当前项目楼号第历史数据
        /// </summary>
        /// <param name="input">筛选条件</param>
        /// <param name="ProjectId">项目id</param>
        /// <param name="BuildingnumberId">楼号id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_ProjectStatuLogDto_>> GetProjectStatuLogList(PageInput<ProjectReturnConditionDTO> input, string ProjectId, string BuildingnumberId)
        {
            var list = await _pB_ProjectBus.GetProjectStatuLogList(input, ProjectId, BuildingnumberId);
            return list;
        }
        /// <summary>
        /// 获取项目下所有楼号
        /// </summary>
        /// <param name="ProjectId">项目id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<PB_Buildingnumber>> GetBulidList(string ProjectId)
        {
            var ListData = await _pB_ProjectBus.GetBulidList(ProjectId);
            return ListData;

        }
        /*
         * 创建人：牟俊明
         * 创建时间：2022-05-13 14:15
         * 描述：添加综合大屏项目详情接口
         */
        /// <summary>
        /// 大屏显示在用机位总数
        /// </summary>
        /// <returns>机位总数</returns>
        [HttpPost]
        [NoCheckJWT]
        public ScreenDisplayValueDTO GetStandsNumberInUsed()
        {
            return _pB_ProjectBus.GetStandsNumberInUsed();
        }
        /// <summary>
        /// 大屏显示已签合同未发货的机位数
        /// </summary>
        /// <returns>已签合同未发货的机位数</returns>
        [HttpPost]
        [NoCheckJWT]
        public ScreenDisplayValueDTO GetReadyDeliveryStandsNumber()
        {
            return _pB_ProjectBus.GetReadyDeliveryStandsNumber();
        }
        /// <summary>
        /// 大屏显示在建的项目总数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public ScreenDisplayValue2DTO GetProjectsunder()
        {
            return _pB_ProjectBus.GetProjectsunder();
        }

        /// <summary>
        /// 大屏显示未发货项目总数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public ScreenDisplayValue2DTO GetTotalNumber()
        {
            return _pB_ProjectBus.GetTotalNumber();
        }
        /// <summary>
        /// 大屏显示交付监控 大屏没有按钮，停用
        /// </summary>
        /// <returns>交付监控</returns>
        //[HttpPost]
        //[NoCheckJWT]
        //public async Task<List<PB_ProjectDeliveryMonitorDTO>> GetPB_ProjectDeliveryMonitor()
        //{
        //    return await _pB_ProjectBus.GetPB_ProjectDeliveryMonitor();
        //}
        /// <summary>
        /// 大屏显示爬架交付状态
        /// </summary>
        /// <returns>爬架交付状态</returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<List<PB_ProjectSubmitStateDTO>> GetProjectSubmitState()
        {
            return await _pB_ProjectBus.GetProjectSubmitState();
        }
        /// <summary>
        /// 大屏显示回货项目数量
        /// </summary>
        /// <returns>回货项目数量</returns>
        [HttpPost]
        [NoCheckJWT]
        public ScreenDisplayValue2DTO GetReturnProjectNumber()
        {
            return _pB_ProjectBus.GetReturnProjectNumber();
        }
        /// <summary>
        /// 大屏显示物料回货百分比均值(先计算单品回货率，再求平均数)
        /// </summary>
        /// <returns>物料回货百分比均值</returns>
        [HttpPost]
        [NoCheckJWT]
        public ScreenDisplayValue3DTO GetReturnAverage()
        {
            return _pB_ProjectBus.GetReturnAverage();
        }
        /// <summary>
        /// 大屏显示30天项目回货率(先计算单品回货率，再求平均数)，损坏率列表。
        /// </summary>
        /// <returns>30天项目回货率，损坏率</returns>
        //[HttpPost]
        //[NoCheckJWT]
        //public async Task<List<PB_ProjectReturnDestoriedRateDTO>> Get30DayReturnDestoriedRate()
        //{
        //    return await _pB_ProjectBus.Get30DayReturnDestoriedRate();
        //}
        [HttpPost]
        [NoCheckJWT]
        public async Task<List<PB_ProjectReturnDestoriedRateDTO>> Get30DayReturnDestoriedRate2()
        {
            return await _pB_ProjectBus.Get30DayReturnDestoriedRate2();
        }
        /// <summary>
        /// 大屏显示 显示所有项目回货信息  项目名称 物料分类  
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<List<ProjectReturnScreen>> ProjectReturnScreens()
        {
            List<ProjectReturnScreen> projectReturnScreensList = await _pB_ProjectBus.ProjectReturnScreensList();
            return projectReturnScreensList;
        }
        [HttpPost]
        public async Task<PageResult<StatisticalData>> GetStatisticalDataAsync(PageInput<ProjectReturnConditionDTO> input) {
            var res =await _pB_ProjectBus.GetStatisticalDataAsync(input);
            return res;
        }
        #endregion
        [HttpPost]
        public async Task<List<DeliveredDeliveryrate>> GETD2(string ProjectId) {
           return  await _pB_ProjectBus.GetD2(ProjectId);
           
        }
        #region 提交

        [HttpPost]
        public async Task SaveData(PB_Project data)
        {
            data.State = 0;
            if (data.Id.IsNullOrEmpty())
            {
                InitEntity(data);

                await _pB_ProjectBus.AddDataAsync(data);
            }
            else
            {
                await _pB_ProjectBus.UpdateDataAsync(data);
            }
        }
        /// <summary>
        /// 获取钉钉项目进度列表
        /// </summary>
        /// <param name="input">筛选条件/param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<PB_ProjectDTO>> GetProjectItemAsync(PageInput<ConditionDTO> input)
        {
            var ProjectItem = await _pB_ProjectBus.GetProjectItemAsync(input);
            return ProjectItem;
        }



        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _pB_ProjectBus.DeleteDataAsync(ids);
        }

        #endregion
    }
}

